﻿using Furion.DependencyInjection;
using ST.Torch.WebApi.Core.Manage.Cache;
using ST.Torch.WebApi.Core.Manager;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ST.Torch.WebApi.Core.Manage
{

    public class RedisCacheContext : ICacheManage, ITransient
    {
        private IDistributedCache _objCache;

        private IMemoryCache _MemoryCache;

        public RedisCacheContext(
            IDistributedCache objCache,
             IMemoryCache MemoryCache
            )
        {
            _objCache = objCache;
            _MemoryCache = MemoryCache;
        }
        #nullable enable
        public T? Get<T>(string key)
        {
            string val=_objCache.GetString(key);
            if (!string.IsNullOrEmpty(val))
            {
                return JsonConvert.DeserializeObject<T>(val);
            }
            else
            {
      
                return default(T);
            }
        }
        public async Task<T?> GetAsync<T>(string key)
        {
            string val = _objCache.GetString(key);
            if (!string.IsNullOrEmpty(val))
            {
                var result= JsonConvert.DeserializeObject<T>(val);
                return await Task.FromResult(result);
            }
            else
            {
                return default(T);
            }
          
        }
        #nullable disable
        public T GetOrCreate<T>(string key, Func<ICacheEntry, T> factory)
        {
            var result = Get<T>(key);
            if (result == null)
            {
                using ICacheEntry entry = _MemoryCache.CreateEntry(key);
            
                var t=factory.Invoke(entry);
                var second = entry.AbsoluteExpirationRelativeToNow.Value.TotalSeconds;
                Set<T>(key, t, (int)second);
                return t;
            }
            else
            {
                return result;
            }
        
        }
        public async Task<T> GetOrCreateAsync<T>(string key, Func<ICacheEntry, Task<T>> factory)
        {
            var result = Get<T>(key);
            if (result == null)
            {
                using ICacheEntry entry = _MemoryCache.CreateEntry(key);

                var t =await factory.Invoke(entry);
                var second = entry.AbsoluteExpirationRelativeToNow.Value.TotalSeconds;
                await SetAsync<T>(key, t, (int)second);
                return t;
            }
            else
            {
                return result;
            }

        }

        public  bool Set<T>(string key, T t, long second=0, bool IsSlidingExpiration = true)
        {
            var obj = Get<T>(key);
            if (obj != null)
            {
                 Remove(key);
            }
            string valStr = JsonConvert.SerializeObject(t);
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
            if (second > 0)
            {
                DateTimeOffset now = DateTimeOffset.Now.AddSeconds(second); // 获取当前时间并包含时区信息
                if (IsSlidingExpiration)
                {
                    options.SlidingExpiration = TimeSpan.FromSeconds(second);
                }
                options.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(second);
            }
             _objCache.SetString(key, valStr, options);   //绝对过期时间
            return true;
            //return await Task.FromResult(true);
        }
        public async Task<bool> SetAsync<T>(string key, T t, long second=0,bool IsSlidingExpiration=true)
        {
            var obj = Get<T>(key);
            if (obj != null)
            {
              await  RemoveAsync(key);
            }
            string valStr = JsonConvert.SerializeObject(t);
            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
            if (second > 0)
            {
                DateTimeOffset now = DateTimeOffset.Now.AddSeconds(second); // 获取当前时间并包含时区信息
                if (IsSlidingExpiration)
                {
                    options.SlidingExpiration = TimeSpan.FromSeconds(second);
                }
                options.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(second);
            }
            await _objCache.SetStringAsync(key, valStr, options);   //绝对过期时间
            return true;
            //return await Task.FromResult(true);
        }

        public bool Remove(string key)
        {
            _objCache.Remove(key);
            return true;
        }
        public async Task<bool> RemoveAsync(string key)
        {
            await _objCache.RemoveAsync(key);
            return true;
            //return await Task.FromResult(true); ;
        }
    }

}
